import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:mesh/function/widgets/animated_tap_widget.dart';
import '../../function/states/activity_state.dart';
import '../../function/states/team_conversation_state.dart';
import '../../function/states/user_state.dart';
import '../../function/models/activity_model.dart';
import '../../function/models/group_chat_model.dart';
import '../../function/routes/app_route_manager.dart';
import '../../function/widgets/border_widget.dart';
import '../../function/widgets/login_dialog.dart';
import '../../function/widgets/group_info_dialog.dart';
import '../../function/widgets/create_team_dialog.dart';

/// 官方内容数据模型
class OfficialContentModel {
  final String contentId;
  final String title;
  final String imageUrl;
  final String videoUrl;
  final List<String> watchingUserIds;

  const OfficialContentModel({
    required this.contentId,
    required this.title,
    required this.imageUrl,
    required this.videoUrl,
    required this.watchingUserIds,
  });
}

/// 发现页面
class DiscoveredPage extends StatefulWidget {
  const DiscoveredPage({super.key});

  @override
  State<DiscoveredPage> createState() => _DiscoveredPageState();
}

class _DiscoveredPageState extends State<DiscoveredPage> {
  // 页面内状态
  int _currentActivityIndex = 0;

  // 官方内容数据
  final List<OfficialContentModel> _officialContentList = [
    OfficialContentModel(
      contentId: 'content_001',
      title: 'Traditional Dance',
      imageUrl: 'assets/images/video1.png',
      videoUrl: 'assets/videos/videoplayback(1).mp4',
      watchingUserIds: ['user_008', 'user_002', 'user_003'],
    ),
    OfficialContentModel(
      contentId: 'content_002',
      title: 'Handicraft',
      imageUrl: 'assets/images/video2.png',
      videoUrl: 'assets/videos/videoplayback(2).mp4',
      watchingUserIds: ['user_003', 'user_004', 'user_005'],
    ),
    OfficialContentModel(
      contentId: 'content_003',
      title: 'Delicacy',
      imageUrl: 'assets/images/video3.png',
      videoUrl: 'assets/videos/videoplayback(3).mp4',
      watchingUserIds: ['user_005', 'user_006', 'user_002'],
    ),
  ];

  @override
  void initState() {
    super.initState();
    // 初始化状态
    ActivityState.initialize();
    TeamConversationState.initialize();

    // 监听用户登录状态变化
    UserState.isLoggedInBeacon.subscribe((isLoggedIn) {
      if (mounted) {
        setState(() {});
      }
    });
    UserState.currentUserBeacon.subscribe((currentUser) {
      if (mounted) {
        setState(() {});
      }
    });

    // 监听群聊状态变化
    TeamConversationState.teamGroupsBeacon.subscribe((_) {
      if (mounted) setState(() {});
    });
  }

  void _handleUserAvatarTap(String userId) {
    if (userId.isEmpty) return;

    final currentUser = UserState.getCurrentUserInfo();
    if (currentUser != null && currentUser.userId == userId) {
      // 如果是当前用户，跳转到自己的用户中心
      AppRouteManager.navigateToUserCenter();
    } else {
      // 如果是其他用户，跳转到其他用户主页
      AppRouteManager.navigateToOtherUserCenter(userId);
    }
  }

  /// 获取当前活动
  ActivityModel? get _currentActivity {
    final activities = ActivityState.getAllActivities();
    if (activities.isEmpty) return null;
    return activities[_currentActivityIndex % activities.length];
  }

  /// 切换到下一个活动
  void _switchToNextActivity() {
    setState(() {
      final activities = ActivityState.getAllActivities();
      if (activities.isNotEmpty) {
        _currentActivityIndex = (_currentActivityIndex + 1) % activities.length;
      }
    });
  }

  /// 根据用户ID获取用户信息
  Map<String, String>? _getUserInfo(String userId) {
    final user = UserState.queryUserById(userId);
    if (user != null) {
      return {'userName': user.userName, 'userAvatar': user.avatar};
    }
    return null;
  }

  /// 格式化群聊创建时间显示
  String _formatGroupCreateTime(DateTime dateTime) {
    return '${dateTime.year}/${dateTime.month.toString().padLeft(2, '0')}/${dateTime.day.toString().padLeft(2, '0')}';
  }

  /// 构建官方内容卡片
  Widget _buildOfficialContentCard(OfficialContentModel content) {
    // 获取观看用户信息
    final watchingUsers =
        content.watchingUserIds
            .take(3)
            .map((userId) {
              return _getUserInfo(userId);
            })
            .where((userInfo) => userInfo != null)
            .toList();

    return GestureDetector(
      onTap: () {
        // 跳转到视频播放页面
        AppRouteManager.navigateToVideoPlayer(content.videoUrl);
      },
      child: Container(
        width: 138.w,
        height: 164.h,
        decoration: BoxDecoration(
          color: const Color(0xFF663507),
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.2),
              blurRadius: 12.r,
              offset: Offset(4.r, 4.r),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 图片部分 - 宽高比 138/94
            Container(
              width: 138.w,
              height: 94.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(12.r),
                  topRight: Radius.circular(12.r),
                ),
                image: DecorationImage(
                  image: AssetImage(content.imageUrl),
                  fit: BoxFit.cover,
                ),
              ),
            ),

            // 内容信息部分
            Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 10.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Spacer(),
                    // 标题
                    Text(
                          content.title,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        )
                        .fontSize(13.sp)
                        .textColor(Colors.white)
                        .fontWeight(FontWeight.w600)
                        .fontFamily(
                          GoogleFonts.quicksand(
                            fontWeight: FontWeight.w600,
                          ).fontFamily,
                        ),
                    Spacer(),
                    // 观看用户
                    if (watchingUsers.isNotEmpty)
                      Row(
                        children: [
                          // 用户头像 - 纵向重叠
                          SizedBox(
                            width:
                                24.w +
                                (watchingUsers.length - 1) *
                                    12.w, // 根据头像数量计算总宽度
                            height: 24.w,
                            child: Stack(
                              children:
                                  watchingUsers
                                      .take(3)
                                      .toList()
                                      .asMap()
                                      .entries
                                      .map((entry) {
                                        final index = entry.key;
                                        final userInfo = entry.value;
                                        return Positioned(
                                          left:
                                              index *
                                              12.w, // 每个头像向左偏移8像素，形成重叠效果
                                          child: Container(
                                            width: 24.w,
                                            height: 24.w,
                                            decoration: BoxDecoration(
                                              shape: BoxShape.circle,
                                              border: Border.all(
                                                color: Colors.white,
                                                width: 1.w,
                                              ),
                                              image: DecorationImage(
                                                image: AssetImage(
                                                  userInfo!['userAvatar']!,
                                                ),
                                                fit: BoxFit.cover,
                                              ),
                                            ),
                                          ),
                                        );
                                      })
                                      .toList(),
                            ),
                          ),

                          SizedBox(width: 6.w),

                          // Watching 文字
                          Text('Watching')
                              .fontSize(13.sp)
                              .textColor(const Color(0xFF4CAF50))
                              .fontWeight(FontWeight.w500)
                              .fontFamily(
                                GoogleFonts.quicksand(
                                  fontWeight: FontWeight.w500,
                                ).fontFamily,
                              ),
                        ],
                      ),

                    Spacer(),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建群聊卡片
  Widget _buildGroupTourCard(GroupChatModel group, int index) {
    final creatorInfo = TeamConversationState.getUserInfo(group.creatorId);
    final creatorAvatar =
        creatorInfo?['userAvatar'] ?? 'assets/images/avatar1.png';

    // 检查当前用户是否已登录
    final currentUser = UserState.getCurrentUserInfo();
    final isLoggedIn = currentUser != null;

    // 检查当前用户是否已加入该群聊
    final isUserInGroup =
        isLoggedIn && group.memberIds.contains(currentUser.userId);

    return GestureDetector(
      onTap: () {
        // 跳转到群聊页面
        AppRouteManager.navigateToConversationChat(
          chatType: 'team',
          chatId: group.groupId,
          chatTitle: group.groupName,
        );
      },
      child: Container(
            width: 343.w,
            height: 72.w,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.centerLeft,
                end: Alignment.centerRight,
                colors: [const Color(0xFF854C14), const Color(0xFF853712)],
              ),
              borderRadius: BorderRadius.circular(8.r),
            ),
            child: Stack(
              clipBehavior: Clip.none,
              children: [
                // 群聊封面图
                Positioned(
                  left: 12.w,
                  bottom: 8.h,
                  child: SizedBox(
                    width: 72.w,
                    height: 80.w,
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.r),
                        image: DecorationImage(
                          image: AssetImage(group.groupCoverImage),
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  ),
                ),

                // 主要内容区域
                Padding(
                  padding: EdgeInsets.fromLTRB(90.w, 6.h, 12.w, 6.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      // 群聊信息
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            // 地点信息
                            Row(
                              children: [
                                Image.asset(
                                  'assets/images/location.png',
                                  width: 16.w,
                                  height: 16.w,
                                ),
                                SizedBox(width: 8.w),
                                Expanded(
                                  child: Text(group.location)
                                      .fontSize(12.sp)
                                      .textColor(Colors.white)
                                      .fontWeight(FontWeight.w500)
                                      .fontFamily(
                                        GoogleFonts.quicksand(
                                          fontWeight: FontWeight.w500,
                                        ).fontFamily,
                                      ),
                                ),
                              ],
                            ),

                            SizedBox(height: 4.h),

                            // 时间信息
                            Row(
                              children: [
                                Image.asset(
                                  'assets/images/time.png',
                                  width: 16.w,
                                  height: 16.w,
                                ),
                                SizedBox(width: 8.w),
                                Text(_formatGroupCreateTime(group.createTime))
                                    .fontSize(12.sp)
                                    .textColor(Colors.white)
                                    .fontWeight(FontWeight.w500)
                                    .fontFamily(
                                      GoogleFonts.quicksand(
                                        fontWeight: FontWeight.w500,
                                      ).fontFamily,
                                    ),
                              ],
                            ),
                          ],
                        ),
                      ),

                      // 创建人头像和加入按钮
                      Row(
                        children: [
                          // 创建人头像
                          GestureDetector(
                            onTap: () => _handleUserAvatarTap(group.creatorId),
                            child: Container(
                              width: 32.w,
                              height: 32.w,
                              decoration: BoxDecoration(
                                shape: BoxShape.circle,
                                image: DecorationImage(
                                  image: AssetImage(creatorAvatar),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                          ),

                          SizedBox(width: 8.w),

                          // 根据用户状态显示不同按钮
                          GestureDetector(
                            onTap: () {
                              if (!isLoggedIn) {
                                // 用户未登录，显示登录弹窗
                                LoginDialog.show(
                                  context,
                                  title: 'Login Required',
                                  message: 'Please login to join group chats',
                                );
                              } else if (!isUserInGroup) {
                                // 用户已登录但未加入群聊，显示群聊信息弹窗
                                GroupInfoDialog.show(context, group);
                              } else {
                                // 用户已加入群聊，跳转到聊天页面
                                AppRouteManager.navigateToConversationChat(
                                  chatType: 'group',
                                  chatId: group.groupId,
                                  chatTitle: group.groupName,
                                );
                              }
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 8.w,
                                vertical: 6.h,
                              ),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(36.r),
                              ),
                              child: Text(isUserInGroup ? 'Chat' : 'Join')
                                  .fontSize(13.sp)
                                  .textColor(const Color(0xFFFF8A3C))
                                  .fontWeight(FontWeight.w600)
                                  .fontFamily(
                                    GoogleFonts.quicksand(
                                      fontWeight: FontWeight.w600,
                                    ).fontFamily,
                                  ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )
          .configBorderWidget(
            borderRadius: 8.r,
            borderColor: Colors.white,
            borderWidth: 1.w,
          )
          .paddingHorizontal(16.w),
    );
  }

  /// 构建活动卡片
  Widget _buildActivityCard(ActivityModel activity) {
    return AnimatedTapWidget(
      onTap:
          () => AppRouteManager.navigateToActivityDetail(activity.activityId),
      child: Container(
        width: double.infinity,
        height: 145.h,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/event-card.png'),
            fit: BoxFit.cover,
          ),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Stack(
          clipBehavior: Clip.none,
          children: [
            // 活动图片 - Stack 在卡片右侧
            Positioned(
              right: 0.w,
              left: 200.w,
              bottom: 0.h,
              child: SizedBox(
                width: 120.w,
                height: 180.w,
                child: Container(
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage(activity.imageUrl),
                      fit: BoxFit.contain,
                    ),
                  ),
                ),
              ),
            ),
            // 活动内容
            Padding(
              padding: EdgeInsets.only(
                left: 12.w,
                right: 12.w,
                top: 14.h,
                bottom: 0.h,
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 左侧内容区域
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 活动标题
                        Text(activity.title)
                            .fontSize(16.sp)
                            .textColor(Colors.white)
                            .fontWeight(FontWeight.w700)
                            .fontFamily(
                              GoogleFonts.quicksand(
                                fontWeight: FontWeight.w700,
                              ).fontFamily!,
                            ),

                        // 活动描述
                        Expanded(
                          child: Text(
                                activity.description,
                                maxLines: 4,
                                overflow: TextOverflow.ellipsis,
                              )
                              .fontSize(14.sp)
                              .textColor(
                                const Color(0xFFFFFFFF).withOpacity(0.9),
                              )
                              .fontWeight(FontWeight.w400)
                              .fontFamily(
                                GoogleFonts.quicksand(
                                  fontWeight: FontWeight.w400,
                                ).fontFamily!,
                              ),
                        ),
                      ],
                    ),
                  ),

                  // 右侧按钮区域
                  Align(
                    alignment: Alignment.bottomRight,
                    child: GestureDetector(
                      onTap: () {},
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(15.r),
                        child: BackdropFilter(
                          filter: ImageFilter.blur(sigmaX: 5.r, sigmaY: 5.r),

                          child: Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 12.w,
                              vertical: 5.h,
                            ),
                            decoration: BoxDecoration(
                              color: Colors.transparent,
                              borderRadius: BorderRadius.circular(15.r),
                              border: Border.all(
                                color: Colors.white.withOpacity(0.2),
                                width: 1.w,
                              ),
                            ),
                            child: Text('View Activities')
                                .fontSize(12.sp)
                                .textColor(Colors.white)
                                .fontWeight(FontWeight.w500)
                                .fontFamily(
                                  GoogleFonts.quicksand(
                                    fontWeight: FontWeight.w500,
                                  ).fontFamily,
                                ),
                          ),
                        ),
                      ),
                    ),
                  ).paddingBottom(12.h),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final currentActivity = _currentActivity;
    final groupTourList = TeamConversationState.getAllTeams();

    return Scaffold(
      extendBody: true,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/community_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 固定标题
              Container(
                constraints: BoxConstraints(maxWidth: 258.h),
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h),
                child:
                    Text('Madagascar Cultural Experience')
                        .fontSize(24.sp)
                        .textColor(Colors.white)
                        .fontWeight(FontWeight.w400)
                        .fontFamily(
                          GoogleFonts.rokkitt(
                            fontWeight: FontWeight.w400,
                          ).fontFamily,
                        )
                        .alignLeft(),
              ),

              SizedBox(height: 12.h),

              // 可滚动内容
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 官方内容横向滚动
                      SizedBox(
                        height: 164.h,
                        child: ListView.builder(
                          scrollDirection: Axis.horizontal,
                          padding: EdgeInsets.symmetric(horizontal: 16.w),
                          itemCount: _officialContentList.length,
                          itemBuilder: (context, index) {
                            final content = _officialContentList[index];
                            return Container(
                              margin: EdgeInsets.only(right: 16.w),
                              child: _buildOfficialContentCard(content),
                            );
                          },
                        ),
                      ),

                      SizedBox(height: 20.h),

                      // 群聊部分
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('Join A Group Tour Together')
                                .fontSize(24.sp)
                                .textColor(Colors.white)
                                .fontWeight(FontWeight.w400)
                                .fontFamily(
                                  GoogleFonts.rokkitt(
                                    fontWeight: FontWeight.w400,
                                  ).fontFamily,
                                ),
                            GestureDetector(
                              onTap: () {
                                // 检查用户登录状态
                                final currentUser =
                                    UserState.getCurrentUserInfo();
                                if (currentUser == null) {
                                  LoginDialog.show(
                                    context,
                                    title: 'Login Required',
                                    message: 'Please login to create a team',
                                  );
                                  return;
                                }

                                // 显示创建群聊弹窗
                                CreateTeamDialog.show(context);
                              },
                              child: Image.asset(
                                'assets/images/add.png',
                                width: 24.w,
                                height: 24.w,
                              ),
                            ),
                          ],
                        ),
                      ),

                      SizedBox(height: 16.h),

                      // 群聊列表
                      if (groupTourList.isNotEmpty)
                        ...groupTourList.asMap().entries.map((entry) {
                          final index = entry.key;
                          final group = entry.value;
                          return _buildGroupTourCard(group, index);
                        }),

                      SizedBox(height: 20.h),

                      // 活动部分
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16.w),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('Event Zone')
                                .fontSize(24.sp)
                                .textColor(Colors.white)
                                .fontWeight(FontWeight.w400)
                                .fontFamily(
                                  GoogleFonts.rokkitt(
                                    fontWeight: FontWeight.w400,
                                  ).fontFamily,
                                ),
                            GestureDetector(
                              onTap: () {
                                // 切换活动
                                _switchToNextActivity();
                              },
                              child: Image.asset(
                                'assets/images/refresh.png',
                                width: 24.w,
                                height: 24.w,
                              ),
                            ),
                          ],
                        ),
                      ),

                      SizedBox(height: 16.h),

                      // 活动卡片
                      if (currentActivity != null)
                        Padding(
                          padding: EdgeInsets.symmetric(horizontal: 16.w),
                          child: _buildActivityCard(currentActivity),
                        ),

                      SizedBox(height: 120.h),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
